const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const moment = require('moment')

exports.main = async event => {
  try {
    const { OPENID } = cloud.getWXContext()
    let curDate = moment().format('YYYY-MM-DD')

    let user = await db
      .collection('user')
      .where({
        id: event.id,
        openid: OPENID,
      })
      .get()

    let days = 0,
      result = 0
    if (user.data.length != 0) {
      let lastDate = user.data[0].date
      days = user.data[0].days
      if (curDate != lastDate) {
        result = await db
          .collection('user')
          .doc(user.data[0]._id)
          .update({
            data: {
              days: days + 1,
              date: curDate,
            },
          })
      }
    }

    return result
  } catch (err) {
    console.log(err)
    return err
  }
}
